package com.leyou.trade.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.auth.com.leyou.auth.utils.UserContext;
import com.leyou.common.exception.LyException;
import com.leyou.item.client.ItemClient;
import com.leyou.item.dto.SkuDTO;
import com.leyou.trade.dto.OrderFormDTO;
import com.leyou.trade.entity.Order;
import com.leyou.trade.entity.OrderDetail;
import com.leyou.trade.entity.OrderLogistics;
import com.leyou.trade.enums.OrderStatus;
import com.leyou.trade.mapper.OrderMapper;
import com.leyou.trade.service.OrderService;
import com.leyou.user.client.UserClient;
import com.leyou.user.dto.AddressDTO;
import feign.FeignException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
    @Autowired
    private OrderDetailServiceImpl detailService;
    @Autowired
    private OrderLogisticsServiceImpl logisticsService;
    @Autowired
    private ItemClient itemClient;
    @Autowired
    private UserClient userClient;

    @Override
    @Transactional
    public Long createOrder(@Valid OrderFormDTO orderDTO) {
        Order order = new Order();
        Long id = UserContext.getUser().getId();
        //用户id
        order.setUserId(id);
        //金额相关信息
        Map<Long, Integer> carts = orderDTO.getCarts();
        ArrayList<Long> longs = new ArrayList<>(carts.size());
        List<SkuDTO> skuDTOS = itemClient.querySkuByIds(longs);
        //计算综合
        long total=0;
        for (SkuDTO skuDTO : skuDTOS) {
            Integer integer = carts.get(skuDTO.getId());
            total+=skuDTO.getPrice()*integer;
        }
        order.setTotalFee(total);
        order.setPaymentType(orderDTO.getPaymentType());
        order.setPostFee(0L);
        order.setActualFee(total+order.getPostFee());
        //初始化订单
        order.setStatus(OrderStatus.INIT.getValue());
        //保存数据库
        boolean save = save(order);
        if(!save){
            throw new LyException(500, "订单创建失败！");
        }
        // 2.写OrderDetail
        // 2.1.定义一个OrderDetail的集合
        ArrayList<OrderDetail> orderDetails = new ArrayList<>();
        for (SkuDTO skuDTO : skuDTOS) {
            Integer integer = carts.get(skuDTO.getId());//商品数量
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(order.getOrderId());
            orderDetail.setImage(StringUtils.substringBefore(skuDTO.getImages(), ","));
            orderDetail.setNum(integer);
            orderDetail.setSkuId(skuDTO.getId());
            orderDetail.setSpec(skuDTO.getSpecialSpec());
            orderDetail.setPrice(skuDTO.getPrice());
            orderDetail.setTitle(skuDTO.getTitle());
            // 2.2.3.装入detail集合
            orderDetails.add(orderDetail);
        }
        boolean b = detailService.saveBatch(orderDetails);
        if(!b){
            throw new LyException(500, "订单创建失败！");
        }
        // 3.写orderLogistics
        // 3.1.查询收货地址
        AddressDTO addressDTO = userClient.queryAddressById(orderDTO.getAddressId());
        OrderLogistics orderLogistics = addressDTO.toEntity(OrderLogistics.class);
        orderLogistics.setOrderId(order.getOrderId());
        boolean save1 = logisticsService.save(orderLogistics);
        if(!save1){
            throw new LyException(500, "订单创建失败！");
        }
        try {
            itemClient.deductStock(carts);
        } catch (FeignException e) {
            throw new LyException(e.status(), e.contentUTF8());
        }
        return order.getOrderId();
    }
}